package com.filter;

import com.qf.entity.UserEmp;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 2019/11/22
 * 郭程鹏
 * gcp1909
 * 面向代码面向君,不负时光不负卿
 */
/*@WebFilter("/*")*/
public class MyFilter implements  Filter{
    //字符集全局变量
    String encoding = null;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        System.out.println("初始化参数");

        encoding ="utf-8";

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("请求前处理");

        HttpServletRequest request = (HttpServletRequest) servletRequest;

        HttpServletResponse response = (HttpServletResponse) servletResponse;

        request.setCharacterEncoding(encoding);

        response.setCharacterEncoding(encoding);

        response.setContentType("text/html;charset=utf-8");

        HttpSession session = request.getSession();

        //请求登录和退出可以进入
        //得到请求路径
        String requestURI = request.getRequestURI();

        if(requestURI.endsWith("login.jsp")|| requestURI.endsWith("login")||requestURI.endsWith(".css")||requestURI.contains("/img")||requestURI.equals("/")||requestURI.contains(".js")){  //放行
            filterChain.doFilter(servletRequest, servletResponse);
        }else{
            UserEmp emp= (UserEmp) request.getSession().getAttribute("user");
            if(emp==null){
                response.setContentType("text/html;charset=utf-8");
                PrintWriter writer = response.getWriter();
                writer.print("<script>alert('请先登录');location.href='login.jsp'</script>");
            }else{
                //放行
                filterChain.doFilter(servletRequest,servletResponse);
            }
        }
    }

    @Override
    public void destroy() {
        System.out.println("摧毁过滤器");
    }

}
